package com.bjsxt.userscenter.springmvc.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.bjsxt.userscenter.auth.pojo.ARoleMenu;
import com.bjsxt.userscenter.auth.service.IAuthService;
import com.bjsxt.userscenter.common.controller.BaseController;
import com.bjsxt.userscenter.common.util.ConstatFinalUtil;
import com.bjsxt.userscenter.common.util.PageInfoUtil;
import com.bjsxt.userscenter.users.pojo.AAdmins;
import com.bjsxt.userscenter.users.pojo.ARole;
import com.bjsxt.userscenter.users.service.IUsersService;

/**
 * 登陆后的管理员操作
 * 
 * url规划:凡是带/back的必须是登陆后才能操作
 * 
 * 
 *
 */
@Controller
@RequestMapping("/back/admins")
public class AdminsBackController extends BaseController
{
	
	@Resource
	private IUsersService usersService;
	@Resource
	private IAuthService authService;
	/**
	 * 登陆后的首页
	 * @return
	 */
	@RequestMapping("/main")
	public String main()
	{
		ConstatFinalUtil.SYS_LOGGER.info("--main--");
		return "/back/admins/main";
	}
	
	//登录后的首页
	@RequestMapping("/leftMenu")
	public String leftMenu(){
		System.out.println("AdminsBackController.leftMenu(左菜单)");
		return "/back/admins/leftMenu";
	}
	//退出登录
	@RequestMapping("/logout")
	public String logout(HttpSession session){
		session.removeAttribute("admins");
		return "redirect:/login.htm" ; 
	}
	
	
	/**
	 * 管理员列表页面
	 * @return
	 */
	@RequestMapping("/adminsList")
	public String adminsList(String keyword,String status,String st,String ed,String currentPage,String pageSize,Model model){
		ConstatFinalUtil.SYS_LOGGER.info("----管理员列表页面----");
		if(status==null){
			status="";
		}
		if(st==null){
			st="";
		}
		if(ed==null){
			ed="";
		}
		/**
		 * 按搜索条件进行查询
		 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("keyword", keyword);
		if(!"".equalsIgnoreCase(status)){
			condMap.put("status", status);
		}
		Date stDate = null ; 
		Date edDate = null ;
		if(!"".equalsIgnoreCase(st)&& !"".equalsIgnoreCase(ed)){
			stDate = this.dateFormatUtil.strDateTime(st); 
			edDate = this.dateFormatUtil.strDateTime(ed);
		}
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);
		PageInfoUtil pageInfoUtil = proccedPageInfo(currentPage, pageSize);
		
		/* 查询结果 */
		/*List<AAdmins> adminsList = this.usersService.findCondListAdminsService(pageInfoUtil,condMap);*/
		Map resultMap = this.usersService.findCondListAdminsService(pageInfoUtil,condMap);
		List<AAdmins> adminsList = (List<AAdmins>) resultMap.get("list");
		pageInfoUtil = (PageInfoUtil) resultMap.get("pageInfoUtil");
		/* 将结果放到四大作用域中 */
		model.addAttribute("adminsList", adminsList);
		model.addAttribute("pageInfoUtil", pageInfoUtil);
		
		/* 将查询条件放到request中 */
		model.addAttribute("keyword", keyword);
		model.addAttribute("status", status);
		model.addAttribute("st", st);
		model.addAttribute("ed", ed);
		return "/back/admins/adminsList";
	}
	/**
	 * 
	 * 管理员添加列表页面先获取角色列表
	 */
	@RequestMapping("/adminsInsert")
	public String adminsInsert(Model model){
		ConstatFinalUtil.SYS_LOGGER.info("------连接到管理员添加页面----------");
		//先查询角色页面
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("status", "1");
		List<ARole> roleList = this.usersService.findCondListRoleService(null, condMap);
		model.addAttribute("roleList", roleList);
		return "/back/admins/adminsInsert";
	}
	/**
	 * 管理员添加页面提交页面
	 * 注意中文乱码处理
	 * @ResponseBody格式原样输出
	 */
	@RequestMapping(value="/adminsInsertSubmit",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String adminsInsertSubmit(HttpServletRequest request,AAdmins admins){
		//如果用户不填写的后台手动赋值
		admins.setPassword(this.encryptUtil.encodeStr(admins.getPassword()));
		/* 时间 */
		admins.setCreateTime(new Date());
		admins.setUpdateTime(new Date());
		admins.setLastLoginTime(new Date());
		JSONObject resDbJSON = this.usersService.saveOneAdminsService(admins);
		//返回的结果保存到INFO中,本次info在实现类里面所获取到的json
		this.info = resDbJSON.getString("info")+""; 
		JSONObject resultJSON = printJuiJson(request,info);
		return resultJSON.toJSONString();
	}
	
	@RequestMapping("/adminsUpdate")
	public String adminsUpdate(String aid,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--adminsUpdate--");
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 根据Id查询管理员 */
		condMap.put("id", aid);
		AAdmins admins = this.usersService.findOneAdminsService(condMap);
		model.addAttribute("admins", admins);
		
		/* 查询所有启用的角色 */
		condMap.clear();
		condMap.put("status", "1");
		List<ARole> roleList = this.usersService.findCondListRoleService(null, condMap);
		model.addAttribute("roleList", roleList);
		return "/back/admins/adminsUpdate"; 
	}
	/**
	 * 
	 * @param request
	 * @param admins
	 * @return 管理员修改页面
	 */
	@RequestMapping(value = "/adminsUpdateSubmit",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String adminsUpdateSubmit(HttpServletRequest request,AAdmins admins){
		//根据ID进行操作
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", admins.getId());
		
		AAdmins adminsRes=this.usersService.findOneAdminsService(condMap);
		adminsRes.setEmail(admins.getEmail());
		adminsRes.setName(admins.getName());
		adminsRes.setPhone(admins.getPhone());
		adminsRes.setQq(admins.getQq());
		adminsRes.setSex(admins.getSex());
		adminsRes.setStatus(admins.getStatus());
		adminsRes.setUpdateTime(new Date());
		//调用json方法进行原样输出
		JSONObject resDbJSON = this.usersService.updateOneAdminsService(adminsRes);
		this.info = resDbJSON.getString("info");
		JSONObject resultJSON = this.printJuiJson(request, info);
		return resultJSON.toJSONString();
	}
	/**
	 * 菜单管理模块
	 */
	@RequestMapping("/menuTreeList")
	public String menuTreeList(Model model){
		ConstatFinalUtil.SYS_LOGGER.info("--menuTreeList--");
		//生成树形结构字符串
		String result = this.authService.proccedMenuTreeStr();
		model.addAttribute("result", result);
		return "/back/admins/menuTreeList" ;
	}
	
	//权限分配页面
	@RequestMapping("/roleMenuInsert")
	public String roleMenuInsert(String roleId,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--roleMenuInsert--");
		
		/* 生成树形结构的字符串 */
		String result = this.authService.proccedMenuTreeStr("roleMenu",roleId);
		/* 存储字符串 */
		model.addAttribute("result", result);
		return "/back/admins/roleMenuInsert" ; 
	}
	
	@RequestMapping(value = "/roleMenuInsertSubmit",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String roleMenuInsertSubmit(HttpServletRequest request,String[] menuId,String roleId)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--roleMenuInsertSubmit--menuId:{}",Arrays.toString(menuId));
		
		/* 默认值 */
		this.info = "操作失败" ; 
		if(menuId != null)
		{
			int totalCount = menuId.length;
			int succedCount = 0; 
			int failedCount = 0;
			
			/*
			 * 删除老数据
			 * */
			Map<String,Object> condMap = new HashMap<String, Object>();
			condMap.put("roleId", roleId);
			this.authService.deleteOneRoleMenuService(condMap);
			
			for (int i = 0; i < menuId.length; i++)
			{
				String meId = menuId[i];
				
				
				try
				{
					/* 往中间表(角色菜单表)增加数据, */
					ARoleMenu roleMenu = new ARoleMenu() ; 
					roleMenu.setMenuId(Integer.valueOf(meId));
					roleMenu.setRoleId(Integer.valueOf(roleId));
					roleMenu.setCreateTime(new Date());
					roleMenu.setUpdateTime(new Date());
					roleMenu.setPubTime(new Date());
					JSONObject resultDbJson = this.authService.saveOneRoleMenuService(roleMenu);
					if("0".equalsIgnoreCase(resultDbJson.getString("code")))
					{
						succedCount ++ ; 
					}else
					{
						failedCount ++ ; 
					}
				} catch (Exception e)
				{
					failedCount ++ ; 
				}
			}
			
			/* 拼装提示信息 */
			this.info = "操作成功,总条数:" + totalCount + ",成功:" + succedCount + ",失败:" + failedCount;
		}
		
		ConstatFinalUtil.SYS_LOGGER.info("权限分配:信息:{},roleId:{},菜单:{}",this.info,roleId,Arrays.toString(menuId));
		JSONObject resultJSON = this.printJuiJson(request, info);
		return resultJSON.toJSONString(); 
	}
}


